package com.cjg.xiancheng;

public class threadPC {
    public static void main(String[] args) {
        wait wait = new wait();

        new Produce(wait).start();
        new Consumer(wait).start();
    }
}
//生成的人
class Produce extends Thread{
    wait wait;

    public Produce(com.cjg.xiancheng.wait wait) {
        this.wait = wait;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            wait.push(new Chicken(i));
            System.out.println("生产了"+i+"鸡");
        }

    }
}
//消费的人
class Consumer extends Thread {
    wait wait;

    public Consumer(com.cjg.xiancheng.wait wait) {
        this.wait = wait;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {

            System.out.println("消费了"+wait.pop().id+"鸡");
        }
    }
}
//产品
class Chicken{
    public int id;

    public Chicken(int i) {
        this.id = i;
    }
}
//缓冲区
class wait{
    //一个 容器 确定大小 ,类能当数组用
    Chicken[] chickens= new Chicken[10];
    //计数器
    int count=0;
    //生产者放入产品
    public synchronized void push(Chicken chicken){
        //如果容器满了 通知 生产者等待 消费者消费

        if (count==chickens.length){

            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //没有满放入产品
        chickens[count]=chicken;
        count++;

        this.notify();

    }

    public synchronized Chicken pop() {
        //判断能否消费
        if (count==0){
            //等待生产者生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Chicken chicken =chickens[count];
        //返回吃了那个鸡
        this.notify();
        return chicken;

    }


}